package com.vbobot.demo.rabbitmq;

import com.google.common.collect.ImmutableMap;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.RabbitListenerEndpointRegistry;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Bobo
 * @date 2022/11/9
 */
@Slf4j
@RestController
public class EndpointController {
    @Resource ApplicationContext applicationContext;

    @Resource RabbitTemplate rabbitTemplate;

    @Resource Optional<RabbitListenerEndpointRegistry> oRabbitListenerEndpointRegistry;

    @GetMapping("/send")
    public String send() {
        AtomicLong value = new AtomicLong(System.currentTimeMillis());
        for (int i = 0; i < 20; i++) {
            final long andAdd = value.getAndAdd(100L);
            final ImmutableMap<String, Long> map = ImmutableMap.of("value", andAdd);
            rabbitTemplate.convertAndSend(RabbitConstats.EXCHANGE, RabbitConstats.ROUTING_KEY, map);
            log.info("send:{}", andAdd);
        }
        return "send";
    }

    @GetMapping("/send/manual")
    public String sendManual() {
        AtomicLong value = new AtomicLong(System.currentTimeMillis());
        for (int i = 0; i < 20; i++) {
            final long andAdd = value.getAndAdd(100L);
            final ImmutableMap<String, String> map = ImmutableMap.of("value", "manual:" + andAdd);
            rabbitTemplate.convertAndSend(RabbitConstats.EXCHANGE_MANUAL, RabbitConstats.ROUTING_KEY, map);
            log.info("send:{}", andAdd);
        }
        return "send";
    }

    @GetMapping("/shutdown")
    public String shutdown() {
        oRabbitListenerEndpointRegistry.ifPresent(registry -> {
            log.info("stop rabbit listener");
            registry.stop();
        });
        return "shutdown";
    }

    @GetMapping("/sleep/{seconds}")
    public String sleepSeconds(@PathVariable("seconds") Integer seconds) {
        MessageListener.SLEEP_SECONDS.set(seconds == null ? 20 : seconds);
        return "sleep to " + seconds + "ms";
    }

    @GetMapping("/graceful/shutdown")
    public String gracefulShutdown() {
        new Thread(() -> SpringApplication.exit(applicationContext)).start();
        return "graceful/shutdown";
    }
}
